package org.playground.booking.utils;


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URLDecoder;

public class HttpUtils {
    private static final Logger LOGGER = Logger.getLogger(HttpUtils.class);

    public static String httpPost(String url, String data, String contentType) throws PlaygroundBookingException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {

            if (data != null && data != "") {
                httpPost.setHeader("content-type", (contentType == null || contentType == "") ? "application/json" : contentType);
                StringEntity entity = new StringEntity(data);
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }

            HttpResponse result = httpClient.execute(httpPost);
            url = URLDecoder.decode(url, "UTF-8");

            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity());
                    return str;
                } catch (Exception e) {
                    LOGGER.error("failed to post:" + url, e);
                    throw new PlaygroundBookingException("failed to post:" + url);
                }
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            throw new PlaygroundBookingException(e.getMessage());
        }
        return "";
    }

    public static String httpGet(String url) throws PlaygroundBookingException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse result = httpClient.execute(httpGet);
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(result.getEntity());
                url = URLDecoder.decode(url, "UTF-8");
                return strResult;
            } else {
                LOGGER.error("get failed:" + url);
                throw new PlaygroundBookingException("failed to get:" + url);
            }
        } catch (IOException e) {
            LOGGER.error("get failed:" + url, e);
            throw new PlaygroundBookingException("failed to get:" + url);
        }
    }

}
